﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 生产管理:生产订单服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class ProductionorderService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Productionorder> _productionorderRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public ProductionorderService(SqlSugarRepository<Productionorder> productionorderRep, ISqlSugarClient sqlSugarClient)
    {
        _productionorderRep = productionorderRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询生产管理:生产订单 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询生产管理:生产订单")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<ProductionorderOutput>> Page(PageProductionorderInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _productionorderRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.ProductionOrderCode.Contains(input.Keyword) || u.ProductionOrderName.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProductionOrderCode), u => u.ProductionOrderCode.Contains(input.ProductionOrderCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProductionOrderName), u => u.ProductionOrderName.Contains(input.ProductionOrderName.Trim()))
            .WhereIF(input.ProductNumber != null, u => u.ProductNumber == input.ProductNumber)
            .WhereIF(input.ProductName != null, u => u.ProductName == input.ProductName)
            .WhereIF(input.CustomerName != null, u => u.CustomerName == input.CustomerName)
            .WhereIF(input.DemandedDateRange?.Length == 2, u => u.DemandedDate >= input.DemandedDateRange[0] && u.DemandedDate <= input.DemandedDateRange[1])
            .WhereIF(input.ProductionOrderNumber != null, u => u.ProductionOrderNumber == input.ProductionOrderNumber)
            .LeftJoin<Products>((u, productNumber) => u.ProductNumber == productNumber.Id)
            .LeftJoin<Products>((u, productNumber, productName) => u.ProductName == productName.Id)
            .LeftJoin<Products>((u, productNumber, productName, unit) => u.Unit == unit.Id)
            .LeftJoin<Client>((u, productNumber, productName, unit, customerName) => u.CustomerName == customerName.Id)
            .Select((u, productNumber, productName, unit, customerName) => new ProductionorderOutput
            {
                Id = u.Id,
                ProductionOrderCode = u.ProductionOrderCode,
                ProductionOrderName = u.ProductionOrderName,
                ProductionOrdeSsource = u.ProductionOrdeSsource,
                ProductNumber = u.ProductNumber,
                ProductNumberFkDisplayName = $"{productNumber.ProductsEncode}",
                ProductName = u.ProductName,
                ProductNameFkDisplayName = $"{productName.ProductsName}",
                SpecificationModel = u.SpecificationModel,
                ProductionSchedule = u.ProductionSchedule,
                Unit = u.Unit,
                UnitFkDisplayName = $"{unit.MeteringUnitId}",
                DatchNumber = u.DatchNumber,
                CustomerName = u.CustomerName,
                CustomerNameFkDisplayName = $"{customerName.CustomerName}",
                DemandedDate = u.DemandedDate,
                ProductionOrderDate = u.ProductionOrderDate,
                DateInProduced = u.DateInProduced,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                ProductionOrderNumber = u.ProductionOrderNumber,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取生产管理:生产订单详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取生产管理:生产订单详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Productionorder> Detail([FromQuery] QueryByIdProductionorderInput input)
    {
        return await _productionorderRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加生产管理:生产订单 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加生产管理:生产订单")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddProductionorderInput input)
    {
        var entity = input.Adapt<Productionorder>();
        return await _productionorderRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新生产管理:生产订单 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新生产管理:生产订单")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateProductionorderInput input)
    {
        var entity = input.Adapt<Productionorder>();
        await _productionorderRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除生产管理:生产订单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除生产管理:生产订单")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteProductionorderInput input)
    {
        var entity = await _productionorderRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _productionorderRep.FakeDeleteAsync(entity);   //假删除
        //await _productionorderRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除生产管理:生产订单 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除生产管理:生产订单")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteProductionorderInput> input)
    {
        var exp = Expressionable.Create<Productionorder>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _productionorderRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _productionorderRep.FakeDeleteAsync(list);   //假删除
        //return await _productionorderRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataProductionorderInput input)
    {
        var productNumberData = await _productionorderRep.Context.Queryable<Products>()
            .InnerJoinIF<Productionorder>(input.FromPage, (u, r) => u.Id == r.ProductNumber)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ProductsEncode}"
            }).ToListAsync();
        var productNameData = await _productionorderRep.Context.Queryable<Products>()
            .InnerJoinIF<Productionorder>(input.FromPage, (u, r) => u.Id == r.ProductName)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ProductsName}"
            }).ToListAsync();
        var unitData = await _productionorderRep.Context.Queryable<Products>()
            .InnerJoinIF<Productionorder>(input.FromPage, (u, r) => u.Id == r.Unit)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.MeteringUnitId}"
            }).ToListAsync();
        var customerNameData = await _productionorderRep.Context.Queryable<Client>()
            .InnerJoinIF<Productionorder>(input.FromPage, (u, r) => u.Id == r.CustomerName)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "productNumber", productNumberData },
            { "productName", productNameData },
            { "unit", unitData },
            { "customerName", customerNameData },
        };
    }
    
    /// <summary>
    /// 导出生产管理:生产订单记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出生产管理:生产订单记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageProductionorderInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportProductionorderOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "生产管理:生产订单导出记录");
    }
    
    /// <summary>
    /// 下载生产管理:生产订单数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载生产管理:生产订单数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportProductionorderOutput>(), "生产管理:生产订单导入模板", (_, info) =>
        {
            if (nameof(ExportProductionorderOutput.ProductNumberFkDisplayName) == info.Name) return _productionorderRep.Context.Queryable<Products>().Select(u => $"{u.ProductsEncode}").Distinct().ToList();
            if (nameof(ExportProductionorderOutput.ProductNameFkDisplayName) == info.Name) return _productionorderRep.Context.Queryable<Products>().Select(u => $"{u.ProductsName}").Distinct().ToList();
            if (nameof(ExportProductionorderOutput.UnitFkDisplayName) == info.Name) return _productionorderRep.Context.Queryable<Products>().Select(u => $"{u.MeteringUnitId}").Distinct().ToList();
            if (nameof(ExportProductionorderOutput.CustomerNameFkDisplayName) == info.Name) return _productionorderRep.Context.Queryable<Client>().Select(u => $"{u.CustomerName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入生产管理:生产订单记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入生产管理:生产订单记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportProductionorderInput, Productionorder>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 产品编号
                    var productNumberLabelList = pageItems.Where(x => x.ProductNumberFkDisplayName != null).Select(x => x.ProductNumberFkDisplayName).Distinct().ToList();
                    if (productNumberLabelList.Any()) {
                        var productNumberLinkMap = _productionorderRep.Context.Queryable<Products>().Where(u => productNumberLabelList.Contains($"{u.ProductsEncode}")).ToList().ToDictionary(u => $"{u.ProductsEncode}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ProductNumber = productNumberLinkMap.GetValueOrDefault(e.ProductNumberFkDisplayName ?? "");
                            if (e.ProductNumber == null) e.Error = "产品编号链接失败";
                        });
                    }
                    // 链接 产品名称
                    var productNameLabelList = pageItems.Where(x => x.ProductNameFkDisplayName != null).Select(x => x.ProductNameFkDisplayName).Distinct().ToList();
                    if (productNameLabelList.Any()) {
                        var productNameLinkMap = _productionorderRep.Context.Queryable<Products>().Where(u => productNameLabelList.Contains($"{u.ProductsName}")).ToList().ToDictionary(u => $"{u.ProductsName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ProductName = productNameLinkMap.GetValueOrDefault(e.ProductNameFkDisplayName ?? "");
                            if (e.ProductName == null) e.Error = "产品名称链接失败";
                        });
                    }
                    // 链接 单位
                    var unitLabelList = pageItems.Where(x => x.UnitFkDisplayName != null).Select(x => x.UnitFkDisplayName).Distinct().ToList();
                    if (unitLabelList.Any()) {
                        var unitLinkMap = _productionorderRep.Context.Queryable<Products>().Where(u => unitLabelList.Contains($"{u.MeteringUnitId}")).ToList().ToDictionary(u => $"{u.MeteringUnitId}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.Unit = unitLinkMap.GetValueOrDefault(e.UnitFkDisplayName ?? "");
                            if (e.Unit == null) e.Error = "单位链接失败";
                        });
                    }
                    // 链接 客户名称
                    var customerNameLabelList = pageItems.Where(x => x.CustomerNameFkDisplayName != null).Select(x => x.CustomerNameFkDisplayName).Distinct().ToList();
                    if (customerNameLabelList.Any()) {
                        var customerNameLinkMap = _productionorderRep.Context.Queryable<Client>().Where(u => customerNameLabelList.Contains($"{u.CustomerName}")).ToList().ToDictionary(u => $"{u.CustomerName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.CustomerName = customerNameLinkMap.GetValueOrDefault(e.CustomerNameFkDisplayName ?? "");
                            if (e.CustomerName == null) e.Error = "客户名称链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Productionorder>>();
                    
                    var storageable = _productionorderRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.ProductionOrderCode?.Length > 32, "订单编码长度不能超过32个字符")
                        .SplitError(it => it.Item.ProductionOrderName?.Length > 32, "订单名称长度不能超过32个字符")
                        .SplitError(it => it.Item.ProductionOrdeSsource?.Length > 32, "订单来源长度不能超过32个字符")
                        .SplitError(it => it.Item.SpecificationModel?.Length > 32, "规格型号长度不能超过32个字符")
                        .SplitError(it => it.Item.DatchNumber?.Length > 32, "批次号长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
